//
// Created by syshen on 2020/5/9.
//

#include "base_util.h"

std::string getDirPath(JNIEnv *env, jstring dirPath) {
    if (NULL == dirPath) {
        return nullptr;
    }
    const char *file_path = env->GetStringUTFChars(dirPath, 0);
    if (NULL == file_path) {
        return nullptr;
    }
    std::string t_file_path = file_path;
    std::string tLastChar = t_file_path.substr(t_file_path.length() - 1, 1);
    //目录补齐/
    if ("\\" == tLastChar) {
        t_file_path = t_file_path.substr(0, t_file_path.length() - 1) + "/";
    } else if (tLastChar != "/") {
        t_file_path += "/";
    }
    return t_file_path;
}

std::string getFilePath(JNIEnv *env, jstring filePath) {
    if (NULL == filePath) {
        return nullptr;
    }
    const char *file_path = env->GetStringUTFChars(filePath, 0);
    if (NULL == file_path) {
        return nullptr;
    }
    return file_path;
}

std::string jstring2str(JNIEnv* env, jstring jstr) {
    char *rtn = NULL;
    jclass clsstring = env->FindClass("java/lang/String");
    jstring strencode = env->NewStringUTF("GB2312");
    jmethodID mid = env->GetMethodID(clsstring, "getBytes", "(Ljava/lang/String;)[B");
    jbyteArray barr = (jbyteArray) env->CallObjectMethod(jstr, mid, strencode);
    jsize alen = env->GetArrayLength(barr);
    jbyte *ba = env->GetByteArrayElements(barr, JNI_FALSE);
    if (alen > 0) {
        rtn = (char *) malloc(alen + 1);
        memcpy(rtn, ba, alen);
        rtn[alen] = 0;
    }
    env->ReleaseByteArrayElements(barr, ba, 0);
    std::string stemp(rtn);
    free(rtn);
    return stemp;
}
